// pages/vip-buy/vip-buy.ts
import api from "../../api/index";
import constants from "../../common/constants";
import common from "../../common/index";
import {uuid} from "../../utils/util";

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    navBarHeight: app.globalData.navBarHeight,
    userInfo: app.globalData.user,

    vipInfo: app.globalData.vipInfo,

    freeCommonDescList: ['AIspire chat，可以使用','灵感发现，可以使用','我的智库，可以使用','30天个性化推送试用'],
    freeDescList: ['我的智库存储空间： 50M','deepseek R1： 5次/每天','deepseek V3：50次/每天','联网搜索：5次/天','文件上传个数：5个/天'],
    plusCommonDescList: ['AIspire chat，可以使用','灵感发现，可以使用','我的智库，可以使用','每日个性化推送'],
    plusDescList: ['我的智库存储空间： 10G','deepseek R1： 50次/每天','deepseek V3：500次/每天','联网搜索：50次/天','文件上传个数：50个/天'],
    proCommonDescList: ['AIspire chat，可以使用','灵感发现，可以使用','我的智库，可以使用','每日个性化推送'],
    proDescList: ['我的智库存储空间： 30G','deepseek R1： 100次/每天','deepseek V3：1000次/每天','联网搜索：200次/天','文件上传个数：200个/天'],
    productInfo: {
      item: {},
      group: {},
    },
    productDescObj: constants.VipRightsDesc,
    productGroupList: [],
    currentBuyGroupIndex: 0,
    currentSwiperIndex: 0,
  },

  handleBack() {
    wx.navigateBack()
  },
  resetProductList(list: any[]) {
    const newList: any[] = [
      {
        "label": "Plus会员",
        code: 'plus',
        spuList: [],
        discountList: [],
      },
      {
        "label": "Pro会员",
        code: 'pro',
        spuList: [],
        discountList: [],
      }
    ]
    list.forEach((group: any) => {
      newList[0].discountList.push({
        discount: group.discount,
        unit: group.unit,
      })
      newList[1].discountList.push({
        discount: group.discount,
        unit: group.unit,
      })
      group.spuList.forEach((item: any) => {
        if (item.levelName === 'plus') {
          newList[0].spuList.push({
            ...item,
            "groupLabel": group.label,
            "groupCode": group.code,
            "groupDiscount": group.discount,
            "groupUnit": group.unit,
            "groupPromotion": group.promotion,
            uid: uuid(8),
          })
        }
        if (item.levelName === 'pro') {
          newList[1].spuList.push({
            ...item,
            "groupLabel": group.label,
            "groupCode": group.code,
            "groupDiscount": group.discount,
            "groupUnit": group.unit,
            "groupPromotion": group.promotion,
            uid: uuid(8),
          })
        }
      })
    })
    console.log('newList', newList)
    return newList
  },
  async getProductList() {
    try {
      this.data.productGroupList = []
      const res = await api.getVipProductList()
      if (res.data && res.data.list) {
        // res.data.list.forEach((prd) => {
        //   const freeIndex = prd.spuList.find((spu) => spu.levelName === 'free')
        //   prd.spuList.splice(freeIndex, 1)
        // })
        this.setData({
          productGroupList: this.resetProductList(res.data.list)
        })
      }
    } catch(e){}
  },
  handleChangeGroup(e: BaseEvent) {
    this.setData({
      currentBuyGroupIndex: e.currentTarget.dataset.index,
      currentSwiperIndex: 0,
    })
  },
  /**
   * swiper change回调事件
   * @param e
   */
  handleSwiperItemChange(e: BaseEvent) {
    if (e.detail.source) {
      this.setData({
        currentSwiperIndex: e.detail.current
      })
    }
  },
  /**
   * 按钮点击改变swiper current
   * @param e
   */
  handleChangeSwiperItem(e: BaseEvent) {
    const index = e.currentTarget.dataset.index
    this.setData({
      currentSwiperIndex: index
    })
  },
  async handlePopBuy(e: BaseEvent) {
    const spuId = e.currentTarget.dataset.id
    wx.showLoading({
      title: '加载中'
    })
    try {
      const res = await api.createVipOrder({spuId})
      if (res.data && res.data.payOrderId) {
        wx.login({
          success: async (data) => {
            if (data.code) {
              const res2 = await api.submitVipOrder({
                id: res.data.payOrderId,
                channelCode: 'wx_lite',
                returnUrl: `https://dev.aispire.xin/pay/cashier?id=467&returnUrl=%252Fpay%252Fdemo%252Forder%253Fid%253D202`,
                channelExtras: {"logincode" : data.code}
              })
              if (res2.data && res2.data.displayContent) {
                const params = JSON.parse(res2.data.displayContent)
                params.package = params.packageValue
                delete params.packageValue
                try {
                  wx.requestPayment({
                    ...params,
                    success: async (data) => {
                      wx.hideLoading()
                      console.log(data)
                    },
                    fail: () => {
                      wx.hideLoading()
                    },
                  })
                } catch (e) {
                  wx.hideLoading()
                  wx.showToast({
                    title: '出现异常',
                    icon: 'error'
                  })
                }
              }
            } else {
              wx.hideLoading()
              wx.showToast({
                title: '微信登录失败',
                icon: 'error'
              })
            }
          }
        })
      } else {
        wx.hideLoading()
        wx.showToast({
          title: '下单失败',
          icon: 'error'
        })
      }
    } catch(e){
      wx.hideLoading()
    } finally {

    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    await this.getProductList()
    const vipInfo = await common.getVipInfo()
    if (vipInfo) {
      common.setAppVipInfo(vipInfo, app.globalData)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})